package edu.whu.puppygo.controller;


import edu.whu.puppygo.base.HttpResponse;
import edu.whu.puppygo.dto.UserDto;
import edu.whu.puppygo.entity.User;
import edu.whu.puppygo.security.JwtTokenUtil;
import edu.whu.puppygo.service.UserService;
import edu.whu.puppygo.vo.LoginResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
@CrossOrigin
@RequestMapping("authenticate")
public class AuthenticationController {

    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private UserService userService;


    @PostMapping("/login")
    public HttpResponse<LoginResult> login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        log.info("username: {}", username);
        //final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userService.findByUsername(username).isPresent()) {
            final String token = jwtTokenUtil.generateToken(username);
            User user = userService.findByUsername(username).get();
            LoginResult loginResult = new LoginResult();
            if (null!=user.getAccount() && !user.getAccount().isEmpty()) {
                loginResult.setAccount(user.getAccount());
            }
            if (null!=user.getNickname() && !user.getNickname().isEmpty()) {
                loginResult.setNikename(user.getNickname());
            }
            if (null!=user.getAvatar() && !user.getAvatar().isEmpty()) {
                loginResult.setAvatar(user.getAvatar());
            }
            loginResult.setUsername(username);
            loginResult.setId(user.getId().toString());
            loginResult.setToken(token);

            return HttpResponse.success(loginResult);
        } else {
            User user = userService.createUser(username);
            final String token = jwtTokenUtil.generateToken(username);
            LoginResult loginResult = new LoginResult();
            loginResult.setUsername(username);
            loginResult.setId(user.getId().toString());
            loginResult.setToken(token);
            return HttpResponse.success(loginResult);
        }
    }
}